import React,{
  useState,useEffect,useRef
} from 'react';
import './viewEditDetail.less';
import http from '@/http';

import { 
  Button,Upload,
  Table,message,
  Input,Select,
  Popconfirm,
  Form
} from 'antd';

import {
  Html5Outlined,
  SettingOutlined,
  DeleteOutlined,
  UploadOutlined
} from '@ant-design/icons';
import icons from './icons';

import formComps from './formComps';
import initData from './initData';
import compDataTemp from './compDataTemp';
import EditModal from './editModal';


function ViewEditDetail(){

  const [comps,setComps] = useState(formComps); 
  const [cData,setCData] = useState(initData); 

  const [formTitle,setFormTitle] =useState("");
  const detailContentRef = useRef();
  const EditModalRef = useRef();
  const [form,setForm] = useState({});

  const [tagType, setTagType] = useState('')
  const [localData, setLData] = useState([]);

  useEffect(()=>{
    const data = JSON.parse(localStorage.getItem('loaclData'))|| []
    setLData(data);
    // eslint-disable-next-line
  },[0])

  function onDragStart(ev,item){
    // console.log(item);
    setTagType(item.name);
  }
 
  function onDragOver(ev){
    ev.preventDefault();
    // console.log('over',ev)
    detailContentRef.current.style.borderColor='lightblue';
    
  }
  
  function onDrop(ev){
    ev.preventDefault();
    if(!tagType) return;

    detailContentRef.current.style.borderColor='#ccc';

    // console.log(ev);
    const temp = compDataTemp[tagType]();

    // return console.log(temp)
    
    temp.left = ev.clientX - ev.target.offsetLeft + 'px';
    temp.top = ev.clientY - ev.target.offsetTop + 'px';

    const data = {...cData};
    data[tagType].push(temp);

    setCData(data);
    setTagType('')
  }

  function showEditModalFn(tag,index){

    let data = { ...cData }
    let item = data[tag][index];
    EditModalRef.current.showModal(item,{tag,index});
  }
  
  function onMouseDown(ev,tag,index){

    let cur = cData[tag][index]
    // return console.log(cur)
    let x = ev.clientX - parseInt(cur.left)
    let y = ev.clientY - parseInt(cur.top);
    
    let data = { ...cData }
    data[tag][index].disX = x;
    data[tag][index].disY = y;
    setCData(data);

    // console.log(x,y)

    document.onmousemove = (ev2) => mouseMove(ev2,tag,index);
    document.onmouseup = () => {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  }
  function mouseMove(ev,tag,index) {
    
    let cur = cData[tag][index];
    const [minX,maxX] = [
      0,detailContentRef.current.offsetWidth - ev.target.offsetWidth
    ]
    const [minY,maxY] = [
      0,detailContentRef.current.offsetHeight - ev.target.offsetHeight
    ]

    let {clientX,clientY} = ev;

    let left = clientX - cur.disX;
    if(left < minX) left = minX;
    if(left > maxX) left = maxX;

    let top = clientY - cur.disY ;
    if(top < minY) top = minY ;
    if(top > maxY) top = maxY ;
    
    let data = { ...cData }
    // console.log(data);
    data[tag][index].left = left + 'px';
    data[tag][index].top = top + 'px';
    setCData(data);
  }

  function editModalSubmitCallback(item,{tag,index}){
    const data = {...cData};
    data[tag][index] = item;
    setCData(data);
  }

  function removeComp(tag,index){
    const data = {...cData};
    data[tag] = data[tag].filter((v,i)=>i!==index);
    setCData(data);
  }
  async function onCompRequest(item,tag,index){
    if(!item.labelName || !item.valueName) {
      const msg = "请设置labelName、valueName"
      return message.warn(msg)
    }
    // return console.log(item);
    const {getOptsApi,method} = item;
    const res = await http[method](getOptsApi);
    const data = {...cData};
    data[tag][index].options = res; 
    setCData(data);
  }

  function onInputChange(e,v){
    setForm({
      ...form,
      [v.fieldName]:e.target.value
    })
  }

  function submit(){
    console.log('form:',form)
    console.log('cData',cData)
  }

  function DragBoxComp(tagName,childComp){
    return cData[tagName].map((v,index)=>(
      <div 
        className="dragBox" 
        key={v.id}
        style={{
          left:v.left,
          top:v.top,
          width:v.width,
          height:v.height,
          zIndex:tagName==='Background'?0:100
        }}
        onMouseDown={(e)=>onMouseDown(e,tagName,index)}
      >
        <Form.Item label={v.label}>
          {childComp(v,index)}
        </Form.Item>
        <div className="editBar">
          <Popconfirm 
            title="确认移除该组件吗？" 
            onConfirm={()=>removeComp(tagName,index)}
            okText="移除"
            cancelText="取消"
          >
            <DeleteOutlined className="del" />
          </Popconfirm>
          <SettingOutlined className="setting" onClick={()=>showEditModalFn(tagName,index)} />
        </div>
      </div>
    ))
  }

  function save(){
    let loaclData = localStorage.getItem('loaclData');
    loaclData = loaclData ? JSON.parse(loaclData) : [];
    
    loaclData.push({
      [loaclData.length + 1]:cData
    })
    
    localStorage.setItem('loaclData',JSON.stringify(loaclData))
  }

  function setLocalData(item){
    console.log(item);
    setCData(item);
  }

  return (
    <div className="viewEditDetail">

      <div className="leftMenu">
        <div className="compBox">
        {comps.map(item =>(
          <div 
            className="comp" 
            key={item.name}
            draggable={true}
            onDragStart={(e)=>onDragStart(e,item)}
          >
            <Html5Outlined className="icon" />
            <span> {item.name}</span>
          </div>
        ))}
        </div>
        
      </div>


      <div 
        className="detailContent" 
        onDragOver={onDragOver} 
        onDrop={onDrop}
        ref={detailContentRef}
        >
          <div className="form-head">
            <Input 
              className="title" 
              value={formTitle} 
              bordered={false}
              placeholder="设置标题..."
              onChange={(e)=>setFormTitle(e.target.value)} 
            />
          </div>
          

          <Form >

            {DragBoxComp(
              'Text',
              (v)=>(
                <p 
                  style={{
                    fontSize:v.fontSize,
                    color:v.color,
                    fontWeight:v.fontWeight
                  }}
                >
                  {v.text}
                </p>
              )
            )}

            {DragBoxComp(
              'Icon',
              (v)=>(
                <p 
                  style={{
                    fontSize:v.fontSize,
                    color:v.color,
                    fontWeight:v.fontWeight
                  }}
                >
                 {icons[v.icon].render()}
                </p>
              )
            )}

            {DragBoxComp(
              'Background',
              (v)=>(
                <div 
                  style={{
                    background:v.background,
                    border:v.border,
                    width:v.width,
                    height:v.height,
                    borderRadius:v.borderRadius,
                    borderColor:v.borderColor
                  }}
                >
                </div>
              )
            )}

            {DragBoxComp(
              'Button',
              (v)=>(
                <Button 
                  type={v.type}
                >
                  {v.text}
                </Button>
              )
            )}

            {DragBoxComp(
              'Upload',
              (v)=>(
                <Upload 
                action={v.action}
                >
                  <Button icon={<UploadOutlined />}>{v.text}</Button>
                </Upload>
              )
            )}

            {DragBoxComp(
              'Input',
              (v)=>(
                <Input 
                  type={v.type}
                  placeholder={v.placeholder}
                  value={form[v.fieldName]}
                  disabled={v.fieldName?false:true}
                  defaultValue={form[v.fieldName]}
                  onChange={(e)=>onInputChange(e,v)}
                />
              )
            )}

            {DragBoxComp(
              'Select',
              (v,index)=>(
                <Select 
                  onChange={(val)=>setForm({...form,[v.fieldName]:val})}
                  onFocus={()=>onCompRequest(v,'Select',index)}
                  disabled={(v.valueName && v.labelName) ? false : true}
                >
                  {v.options.map(opt=>(
                    <Select.Option key={opt[v.valueName]} value={opt[v.valueName]}>{opt[v.labelName]}</Select.Option>
                  ))}
                  
                </Select>
              )
            )}
          
          </Form>
         
         
         <div className="footer">
           <Button type="primary" onClick={submit}>提交</Button>
           <Button className="save" onClick={save}>保存</Button>
         </div>
      </div>

      <div className="rigBox">
        {localData.map((item,i) =>(
          <span key={i} onClick={()=>setLocalData(item[i + 1])}>存档{i + 1}</span>
        ))}
        
      </div>

      <EditModal 
        ref={EditModalRef} 
        submitCallback={editModalSubmitCallback}
      />
    </div>
  )
}

export default ViewEditDetail;